//
//  CommitSupervisionController.m
//  HZHome
//
//  Created by Alawn on 13-9-23.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "CommitSupervisionController.h"
#import "MKNetworkKit.h"
#import "ConfigManage.h"
#import "ListViewController.h"
#import "UserInfoService.h"
#define INPUT_VIEW_OFFSET 100.0
@interface CommitSupervisionController ()

@end

@implementation CommitSupervisionController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (self.config!=nil) {
        NSString *myValue=[self.config objectForKey:@"key"];
        self.title=myValue;
        if ([myValue compare:@"市场监管"]==NSOrderedSame) {
            complainType=@"0";
            serviceOrgName=@"区工商局";
            self.txtBottomMessage.text=@"市民群众发现自己的合法消费者权益受到侵害时，请随时拨打12345或者通过举报平台向监督部门进行举报。";
        }
        if ([myValue compare:@"市容环境"]==NSOrderedSame) {
            complainType=@"1";
            serviceOrgName=@"区环保局";
            self.txtBottomMessage.text=@"市民群众发现任何影响我区市容环境、卫生的情况，请随时拨打12369或者通过举报平台向监督部门进行举报。";
        }
        if ([myValue compare:@"公车监督"]==NSOrderedSame) {
            complainType=@"2";
            serviceOrgName=@"区监察局";
            self.txtBottomMessage.text=@"欢迎市民群众监督我区公车的使用管理。市民群众发现任何涉及我区公务车涉嫌私用的线索，可以通过拨打12388举报电话或者通过举报平台向监管部门进行举报。";
        }
    }
      self.navigationItem.rightBarButtonItem = getCustomNavButton(@"监督记录", self, @selector(rightBtAction:));
    self.navigationItem.leftBarButtonItem = autoavBackButton(self, @selector(backMethod));
    self.txtTittle.inputAccessoryView = [self getInputAccessoryView];
     self.txtContent.inputAccessoryView = [self getInputAccessoryView];
    self.txtName.inputAccessoryView = [self getInputAccessoryView];
    self.txtPhone.inputAccessoryView = [self getInputAccessoryView];
    [_scrollView addSubview:_formPanelView];
    _scrollView.contentSize = _formPanelView.frame.size;
    self.title=@"我要监督";
    self.txtName.delegate = self;
    self.txtName.tag = 1;
    self.txtPhone.delegate = self;
    self.txtPhone.tag = 2;
}

-(void)backMethod
{
    [DataStoreService deleteFromKeychain:COMPLAINTYPE];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Button Methods
-(void)rightBtAction:(id)sender
{
    ListViewController *listVC = [[ListViewController alloc]initWithNibName:@"ListViewController" bundle:nil];
    NSDictionary *vcConfig =nil;
    if ([complainType compare:@"0"]==NSOrderedSame) {
        vcConfig=[NSDictionary dictionaryWithObjectsAndKeys:@"市场监管监督",@"key",nil];
    }
    if ([complainType compare:@"1"]==NSOrderedSame) {
        vcConfig=[NSDictionary dictionaryWithObjectsAndKeys:@"市容环境监督",@"key",nil];
    }
    if ([complainType compare:@"2"]==NSOrderedSame) {
        vcConfig=[NSDictionary dictionaryWithObjectsAndKeys:@"公车违规监督",@"key",nil];
    }
    listVC.config=vcConfig;
    [DataStoreService saveToKeychain:COMPLAINTYPE data:complainType];
    [self.navigationController pushViewController:listVC animated:YES];
}

-(IBAction)selectPhotoMethod:(id)sender
{
    //在这里呼出下方菜单按钮项
    myActionSheet = [[UIActionSheet alloc]
                     initWithTitle:nil
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];
    
    [myActionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    //呼出的菜单按钮点击后的响应
    if (buttonIndex == myActionSheet.cancelButtonIndex)
    {
        NSLog(@"取消");
    }
    
    switch (buttonIndex)
    {
        case 0:  //打开照相机拍照
            [self takePhoto];
            break;
            
        case 1:  //打开本地相册
            [self LocalPhoto];
            break;
    }
}


//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
//        [self presentModalViewController:picker animated:YES];
        [self presentViewController:picker animated:YES completion:^{
            //
        }];
    }else
    {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
//    [self presentModalViewController:picker animated:YES];
    [self presentViewController:picker animated:YES completion:^{
        //
    }];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        
        //关闭相册界面
//        [picker dismissModalViewControllerAnimated:YES];
        [picker dismissViewControllerAnimated:YES completion:^{
            //
        }];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
//        UIImageView *smallimage = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 40, 40)];
        
        self.imgViewSelect.image = image;
    } 
    
}



- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
//    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:^{
        //
    }];
}



-(void)sendInfo
{
    NSLog(@"图片的路径是：%@", filePath);
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)showAlert:(NSString *) msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
//提交事件
-(IBAction)commitMethod:(id)sender
{
    NSString *strTittle=[self.txtTittle text];
    NSString *strContent=[self.txtContent text];
    if (strTittle.length==0||strContent.length==0) {
        [self showAlert:@"请认真填写信息"];
        return;
    }
    MKNetworkEngine *engine =nil;
    if (filePath) {
        engine=[[MKNetworkEngine alloc] initWithHostName:WoYaoJianDu2 customHeaderFields:nil];
    }
    else
    {
          engine=[[MKNetworkEngine alloc] initWithHostName:WoYaoJianDu1 customHeaderFields:nil];
    }
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:strTittle forKey:@"title"];
    [dic setValue:strContent forKey:@"complainContent"];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    NSString *currentLoginUserName=@"";
    NSString *mobile=@"";
    if (userInfo.currentLoginUserName && userInfo.currentLoginUserName.length>0) {
        currentLoginUserName=userInfo.currentLoginUserName;
        mobile=userInfo.userInfo.mobile;
    }
    else
    {
        [dic setValue:getDeviceIdentifier() forKey:@"imeiCode"];//要加入的唯一标示
    }
    [dic setValue:userInfo.userInfo.Id forKey:@"userId"];
    [dic setValue:currentLoginUserName forKey:@"userName"];
    [dic setValue:self.txtPhone.text forKey:@"phone"];
    [dic setValue:self.txtName.text forKey:@"name"];
    [dic setValue:getDeviceIdentifier() forKey:@"imsi_code"];//要加入的唯一标示
    [dic setValue:complainType forKey:@"complainType"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
    [dic setValue:strDate forKey:@"complainTime"];
    [dic setValue:@"0" forKey:@"dealStatus"];
    [dic setValue:serviceOrgName forKey:@"serviceOrgName"];
    MKNetworkOperation *op = [engine operationWithPath:@"" params:dic httpMethod:@"POST"];
    if (filePath) {
//        [op addFile:filePath forKey:@"media" mimeType:@"application/octet-stream"];
        [op addFile:filePath forKey:@"media" mimeType:@"image/jpeg"];
    }
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
            NSLog(@"[operation responseData]-->>%@", [operation responseString]);
            NSDictionary *json = [operation responseJSON];
        dealCode=[json objectForKey:@"dealCode"];
        [self loadDataFinished];
        }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
            NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
            [self loadDataFaild:[err localizedDescription]];
        }];
        [engine enqueueOperation:op];
    [self startLoadingView];
}
-(void)startLoadingView
{
    loadingView = [[MBProgressHUD alloc]initWithView:self.view];
    loadingView.labelText = @"正在提交...";
    [self.view addSubview:loadingView];
    [loadingView show:YES];
}
-(void)loadDataFinished
{
    [loadingView removeFromSuperview];
    loadingView = nil;
    NSString *tipMessage=[NSString stringWithFormat:@"您提交的信访事项（受理编号\n%@）已转有关单位办理，您可以凭受理编号查询办理情况",dealCode];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:tipMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)loadDataFaild:(NSString *)msg
{
    [loadingView removeFromSuperview];
    loadingView = nil;
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
///开始输入举报内容
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
    textView.text=[NSString stringWithFormat:@"%@,",strDate];
}

#pragma mark - Text Field Delegate
//开始输入的时候向上移动整个界面，这个输入框不会被挡住
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y - INPUT_VIEW_OFFSET * textField.tag;
    self.view.frame = frame;
    [_scrollView scrollRectToVisible:CGRectMake(0, CGRectGetMinY(textField.frame), 320, 200) animated:NO];
    [UIView commitAnimations];
}

//输入结束的时候把整个界面向下移动，这个能恢复正常
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + INPUT_VIEW_OFFSET * textField.tag;
    self.view.frame = frame;
    [UIView commitAnimations];
}
@end





